package com.atguigu.gmall.realtime.app;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/28 8:56
 */
public abstract class BaseSqlApp {
    
    public abstract void run(StreamTableEnvironment tenv);
    
    public void init(int port,
                     int parallelism,
                     String ck) {
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", port);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(parallelism);
        
        // 1. 设置精准一次性保证（默认）  每5000ms开始一次checkpoint
        env.enableCheckpointing(3000, CheckpointingMode.EXACTLY_ONCE);
        // 2. Checkpoint必须在一分钟内完成，否则就会被抛弃
        env.getCheckpointConfig().setCheckpointTimeout(60000);
        // 3.开启在 job 中止后仍然保留的 externalized checkpoints
        env
            .getCheckpointConfig()
            .enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        // 4. 设置状态后端
        //        env.setStateBackend(new FsStateBackend("hdfs://hadoop162:8020/gmall2021/flink/ck/" + ck));
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop162:8020/gmall2021/flink/ck/" + ck);
    
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        run(tenv);
    
        try {
            env.execute(ck);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
